package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ruoyi.system.domain.HszClazz;
import com.ruoyi.system.mapper.HszClazzMapper;
import com.ruoyi.system.service.IHszClazzService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.ruoyi.system.domain.table.HszClazzTableDef.HSZ_CLAZZ;


@Service
public class HszClazzServiceImpl extends ServiceImpl<HszClazzMapper, HszClazz> implements IHszClazzService {
    /**
     * 获取当前id及其子集id
     *
     * @param clazzId 克拉兹 ID
     * @return {@link List }<{@link Long }>
     */
    @Override
    public List<Long> getChildClazzIds(Long clazzId) {
        List<Long> cycleClazz = cycleClazz(new ArrayList<Long>(Arrays.asList(clazzId)));
        cycleClazz.add(clazzId) ;
        return cycleClazz;
    }

    /**
     * 拼接树结构
     *
     * @param clazzs 克拉兹
     */
    @Override
    public void cycleClazzTree(List<HszClazz> clazzs){
        if(CollectionUtil.isEmpty(clazzs)){
            return;
        }
        clazzs.forEach(clazz -> {
            List<HszClazz> childList = this.list(QueryWrapper.create().from(HszClazz.class).where(HSZ_CLAZZ.PID.eq(clazz.getClazzId())).orderBy(HSZ_CLAZZ.SORT.asc()));
            if(CollectionUtil.isNotEmpty(childList)){
                clazz.setChildClazz(childList);
                cycleClazzTree(childList);
            }
        });
    }

    /**
     * 获取子集id(不包括自身层级)
     * @param clazzIds
     * @return {@link List }<{@link Long }>
     */
    @Override
    public List<Long> cycleClazz(List<Long> clazzIds){
        List<Long> resultList = new ArrayList<>();
        List<HszClazz> list = this.list(QueryWrapper.create().from(HszClazz.class).where(HSZ_CLAZZ.PID.in(clazzIds)));
        if(CollectionUtil.isNotEmpty(list)){
            List<Long> idCollect = list.stream().map(HszClazz::getClazzId).collect(Collectors.toList());
            resultList.addAll(idCollect);
            resultList.addAll(cycleClazz(idCollect)); // 循环
        }
        return resultList;
    }

    /**
     * 获取路径
     *
     * @param clazz
     * @return
     */
    @Override
    public HszClazz path(HszClazz clazz){
        if (Objects.isNull(clazz.getPid())){
            return clazz;
        }
        HszClazz parent = this.getById(clazz.getPid());
        if (Objects.nonNull(parent)){
            parent.setChildClazz(new ArrayList<HszClazz>(Arrays.asList(clazz)));
            parent = path(parent);
        }
        return parent;
    }

}
